<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/30
 * Time: 10:58
 */

namespace app\api\controller;
use app\admin\model\Integral;
use \app\api\model\Poi as M;
use app\common\controller\Api;
use think\db;
use think\Exception;
use think\Request;
use think\Config;

class Poi extends Api
{
    public function index(){
        $id=input('poi_id');
        $openid=input('openid');
        $m=new M();
        $data= $m->details($id,$openid);
        return json_encode($data);
    }
    //展示poi评论列表
    public function showPoiComment()
    {
        $post = request()->post();
        if(isset($post['poi'])){
            $where['poi_id'] = $post['poi'];
        }
        if(isset($post['page'])){
            $page= $post['page'];
        }else{
            $page = 1;
        }
        if(isset($post['offset'])){
            $offset= $post['offset'];
        }else{
            $offset = 15;
        }
        $where['is_show'] = 1;

        $list = db("poi_comment pc")
            ->field('pc.comment_id,pc.poi_id,
            pc.content,pc.create_at,pc.content_img,pc.score,pc.user_id,
            pc.is_top,pc.is_good,pc.is_anonymous,
            m.member_nickname as username,
            th.filepath as userface')
            ->join("tplay_member m","m.member_id=pc.user_id",'LEFT')
            ->join("tplay_attachment th","th.id=m.thumb",'LEFT')
            ->where($where)
            ->order("pc.is_top desc,pc.is_good desc,pc.create_at desc")
            ->page($page,$offset)
            ->select();
        foreach ($list as $key=>$value){
            if(!empty($value['content_img'])){
                $list[$key]['content_img'] = explode(',',$value['content_img']);
            }else{
                $list[$key]['content_img'] = [];
            }
            if(empty($value['username']) || $value['is_anonymous']==1){
                //默认名称
                $list[$key]['username'] = '匿名';
                //默认头像
                $list[$key]['userface'] = Config::get('default_userface');
            }
            if(empty($value['score'])){
                //默认名称
                $list[$key]['score'] = 0;
            }
            $list[$key]['create_at'] = date("Y-m-d H:i:s",$value['create_at']);
        }

        return json(['code'=>0,'msg'=>'获取列表成功','data'=>$list]);
    }

    //添加poi评论 by wtt 2019-04-01
    public function addPoiComment()
    {
        $post = request()->post();
        if(!isset($post['poi'])){
            return json(['code'=>-1,'msg'=>'缺少poi参数']);
        }
        //检查数据的有效性
        $poi = db('poi')->find($post['poi']);
        if(empty($poi)){
            return json(['code'=>-1,'msg'=>'poi信息有误']);
        }
        if(!isset($post['content'])){
            return json(['code'=>-1,'msg'=>'缺少content参数']);
        }
        if(isset($post['score'])){
            $score = $post['score'];
        }else{
            $score = 0;
        }
        if(isset($post['anonymous'])){
            $anonymous = $post['anonymous'];
        }else{
            $anonymous = 0;
        }
        if(isset($post['content_img']) && !empty($post['content_img'])){
            if(count($post['content_img'])>9){
                return json(['code'=>-1,'msg'=>'最多只能上传9张图片']);
            }
            $content_img = implode(',',$post['content_img']);
        }else{
            $content_img = '';
        }
        if(isset($post['openid'])){
            $member= db('member')->where('program_openid',$post['openid'])->find();
            $user_id = empty($member['member_id'])?0:$member['member_id'];
        }else{
            $user_id = 0;
        }
        if(isset($post['from'])){
            $from = $post['from'];
        }else{
            $from = "wap";
        }
        $ip = request()->ip();
        //开启事务
        db::startTrans();
        $insert = [
            'user_id'=>$user_id,
            'is_anonymous'=>$anonymous,
            'poi_id'=>$post['poi'],
            'content'=>$post['content'],
            'score'=>$score,
            'content_img'=>$content_img,
            'create_at'=>time(),
            'from'=>$from,
            'ip'=>$ip
        ];

        $res = db('poi_comment')->insert($insert);
        $comment_id = db('poi_comment')->getLastInsID();
        if($res){
            try{
                //更新poi的评价总分和评价总人数
                db('poi')->where('id',$post['poi'])->update([
                    'total_score'=>$poi['total_score']+$score,
                    'total_comment_num'=>$poi['total_comment_num']+1
                ]);
                //增加poi图片库
                $this->addPoiCommentImgs($comment_id,$content_img,'customer');
                //赠送积分
                if($user_id){
                    $this->addIntegrationByPOIComment($user_id);
                }
                //成功提交
                db::commit();
                return json(['code'=>0,'msg'=>'评论成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,'msg'=>'评论失败']);
            }
        }else{
            db::rollback();
            return json(['code'=>-1,'msg'=>'评论失败']);
        }
    }

    public function addPoiCommentImgs($comment_id,$content_img,$source=""){
        $comment = db("poi_comment")->find($comment_id);
        if(!empty($comment)){
            if(!empty($content_img)){
                $content_img = explode(",",$content_img);
                if(!empty($content_img)){
                    $insert_data = [];
                    foreach ($content_img as $k=>$v){
                        $insert_data[] = [
                          'poi_id'=>$comment['poi_id'],
                          'img_src'=>$v,
                          'comment_id'=>$comment_id,
                          'source'=>$source
                        ];
                    }
                    if(!empty($insert_data)){
                        db("poi_images")->insertAll($insert_data);
                    }
                }
            }
        }
    }

    //poi评论获取积分
    public function addIntegrationByPOIComment($member_id)
    {
        //获取POI评论的基数
        $integral = (new Integral())->getIntegralNumber(3);
        db("member_integrallog")->insert([
            'member_id'=>$member_id,
            'describe'=>'POI评论所得',
            'integral'=>$integral,
            'create_time'=>time()
        ]);

        db("member")->where("member_id",$member_id)->setInc("member_integral",$integral);
    }

    //获取产品中全部已启用的门票
    public function getProductTicket($product_id){
        $data = db("pactive")
            ->alias("a")
            ->join("pschedule s","a.groupid=s.id","LEFT")
            ->join("product p","s.groupid=p.id","LEFT")
            ->where("p.id",$product_id)
            ->where("a.ticket_status",1)
            ->field("a.poiid")
            ->select();

        $ticketData = [];
        foreach ($data as $key=>$value) {
            $poiid = $value['poiid'];
            $ticketPriceData = db("ticketprice")
                ->alias("t")
                ->join("poi p","t.poiid=p.id","LEFT")
                ->where("p.id",$poiid)
                ->field("t.id,t.name,t.sale_price,t.cost_price,t.currency,t.default,p.name as poiname,p.eng_name,p.ticket_last_admin,p.ticket_last_updtime,t.charge_type")
                ->select();

            foreach ($ticketPriceData as $k=>$v) {
                if(!empty($v['eng_name'])){
                    $v['poiname'] = $v['poiname']."(".$v['eng_name'].")";
                }
                unset($v['eng_name']);
            }
            if(!empty($ticketPriceData)){
            $ticketData[] = [
                'poiname'=>$ticketPriceData[0]['poiname'],
                'ticket'=>$ticketPriceData
            ];
            }
        }

        return $ticketData;
    }



}